package com.gitee.feizns.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

/**
 * 流
 * @author feizns
 * @since 2019/5/13
 */
public abstract class StreamUtils {

    /**
     * copy流
     * @param is
     * @param length
     * @return
     * @throws IOException
     */
    public static InputStream[] copyStream(InputStream is, int length) {
        InputStream[] result = new InputStream[length];
        try {
            byte[] tmp = new byte[is.available()];
            is.read(tmp);
            for (int i = 0; i < length; i++) {
                result[i] = new ByteArrayInputStream(tmp);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * copy流
     * @param is
     * @return
     * @throws IOException
     */
    public static InputStream copyStream(InputStream is) {
        return copyStream(is, 1)[0];
    }

    /**
     * copy多流
     * @param os
     * @param length
     * @return
     * @throws IOException
     */
    public static InputStream[] copyStream(ByteArrayOutputStream os, int length) {
        InputStream[] result = new InputStream[length];

        byte[] bytes = os.toByteArray();

        for (int i = 0; i < length; i++)
            result[i] = new ByteArrayInputStream(bytes);

        return result;
    }

    /**
     * copy流
     * @param os
     * @return
     * @throws IOException
     */
    public static InputStream copyStream(ByteArrayOutputStream os) {
        return copyStream(os, 1)[0];
    }

    /**
     * 关闭流
     * @param closeables
     */
    public static void close(Closeable... closeables) {
        for (int i = 0; i < closeables.length; i++) {
            try {
                closeables[i].close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
